<template>
  <div>
    <div :id="id" style="margin-bottom:15px;min-width:650px"></div>
    <a-button @click="editHTML" icon="form" style="margin-right:5px">编辑HTML代码</a-button>
    <a-button @click="fullscreenModal=true" icon="eye" style="margin-right:5px">全屏预览</a-button>
    <a-button @click="clear" icon="delete">清空</a-button>

    <a-modal
      title="编辑html代码"
      v-model="showHTMLModal"
      :mask-closable="false"
      :width="900"
    >
      <a-textarea
        v-if="!full"
        :id="id"
        v-model="dataEdit"
        :rows="15"
        style="max-height:55vh;overflow:auto;"
      />
      <a-textarea :id="id" v-if="full" v-model="dataEdit" :rows="32"/>
      <div slot="footer">
        <a-button @click="full=!full" icon="expand">全屏开/关</a-button>
        <a-button @click="editHTMLOk" type="primary" icon="checkmark-circle-outline">确定保存</a-button>
      </div>
    </a-modal>
    <a-modal title="预览" v-model="fullscreenModal" wrapClassName="showMax">
      <div v-html="data">{{data}}</div>
      <div slot="footer">
        <a-button @click="fullscreenModal=false">关闭</a-button>
      </div>
    </a-modal>
  </div>
</template>

<script>
  import E from 'wangeditor'
  import Vue from 'vue'
  // 表情包配置 自定义表情可在该js文件中统一修改
  import { sina } from '../utils/emoji'

  var editor = null
  var xss = require('xss')
  export default {
    name: 'flyme-editor',
    model: {
      prop: 'value',
      event: 'change.value'
    },
    props: {
      id: {
        type: String,
        default: 'editor'
      },
      value: {
        type: [String, Object],
        default: null
      },
      openXss: {
        type: Boolean,
        default: false
      }
    },
    data() {
      return {
        editor: null,
        data: this.value, // 富文本数据
        dataEdit: '', // 编辑数据
        showHTMLModal: false, // 显示html
        full: false, // html全屏开关
        fullscreenModal: false // 显示全屏预览
      }
    },
    methods: {

      initEditor() {
        let that = this
        editor = new E(`#${this.id}`)
        // 编辑内容绑定数据
        editor.customConfig.onchange = html => {
          if (this.openXss) {
            this.data = xss(html)
          } else {
            this.data = html
          }
          this.$emit('input', this.data)
          this.$emit('change', this.data)
        }
        // z-index
        editor.customConfig.zIndex = 100
        // 配置上传图片服务器端地址
        editor.customConfig.uploadImgServer = this.api.file.upload
        // xboot如要header中传入token鉴权
        editor.customConfig.uploadImgHeaders = {
          Authorization: Vue.ls.get('Access-Token')
        }
        editor.customConfig.uploadFileName = 'file'
        editor.customConfig.uploadImgHooks = {
          before: function(xhr, editor, files) {
            that.$message.loading('图片上传中...')
            // 图片上传之前触发
          },
          success: function(xhr, editor, result) {
            // 图片上传并返回结果，图片插入成功之后触发
          },
          fail: function(xhr, editor, result) {
            // 图片上传并返回结果，但图片插入错误时触发
            that.$Message.error('上传图片失败')
          },
          error: function(xhr, editor) {
            // 图片上传出错时触发
            that.$Message.error('上传图片出错')
          },
          timeout: function(xhr, editor) {
            // 图片上传超时时触发
            that.$Message.error('上传图片超时')
          },
          // 如果服务器端返回的不是 {errno:0, data: [...]} 这种格式，可使用该配置
          customInsert: function(insertImg, result, editor) {
            if (result.code == 100) {
              let url = result.data.url
              if (result.data.ossPath != '') {
                that.timer = window.setInterval(function() {
                  let imgObj = new Image()
                  imgObj.src = url
                  if (imgObj.fileSize > 0 || (imgObj.width > 0 && imgObj.height > 0)) {
                    clearInterval(that.timer)
                    insertImg(url)
                    that.$message.destroy()
                    that.$message.success('上传成功')
                  }
                }, 1000)
              } else {
                url += '/original'
                insertImg(url)
                that.$message.destroy()
                that.$message.success('上传成功')
              }

            } else {
              that.$Message.error(result.data.message)
            }
          }
        }
        editor.customConfig.customAlert = function(info) {
          // info 是需要提示的内容
          // that.$Message.info(info);
        }
        // 字体
        editor.customConfig.fontNames = ['微软雅黑', '宋体', '黑体', 'Arial']
        // 表情面板可以有多个 tab ，因此要配置成一个数组。数组每个元素代表一个 tab 的配置
        editor.customConfig.emotions = [
          {
            // tab 的标题
            title: '新浪',
            // shopType -> 'emoji' / 'image'
            type: 'image',
            // content -> 数组
            content: sina
          }
        ]
        editor.create()

        if (this.value) {
          if (this.openXss) {
            editor.txt.html(xss(this.value));
          } else {
            editor.txt.html(this.value);
          }
        }
      },
      editHTML() {
        this.dataEdit = this.data
        this.showHTMLModal = true
      },
      editHTMLOk() {
        editor.txt.html(this.dataEdit)
        if (this.openXss) {
          this.data = xss(this.dataEdit)
        } else {
          this.data = this.dataEdit
        }
        this.$emit('input', this.data)
        this.$emit('change', this.data)
        this.showHTMLModal = false
      },
      clear() {
        this.$confirm({
          title: '确认清空',
          content: '确认要清空编辑器内容？清空后不能撤回',
          onOk: () => {
            this.data = ''
            editor.txt.html(this.data)
            this.$emit('input', this.data)
            this.$emit('change', this.data)
          }
        })
      },
      setValueData(value) {
        this.data = value
        this.$emit('input', this.data)
        this.$emit('on-change', this.data)
      },
      setData(value) {
        if (!editor) {
          this.initEditor();
        }
        this.data = value
        editor.txt.html(this.data)
        // this.$emit('input', this.data)
        //this.$emit('change', this.data)
      }
    },
    watch: {
      value(val) {
        console.info('editor', val)
        this.setData(val)
      }
    },
    mounted() {
      this.$nextTick(function() {
        this.initEditor()
        if (this.value) {
          this.setData(this.value)
        }
      })

    },
    created() {

    }
  }
</script>

<style lang="less" scoped>

</style>

